﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
using FFSupplier.Common.CustomException;

namespace FFSupplier.Common.CustomContext
{
    public abstract class ContextBase<T> : IContext<T>
    {
        public T Current
        {
            get
            {
                object obj = CallContext.GetData(GetKey());
                if (obj == null)
                {
                    return default(T);
                    //throw new NullContextDataException(string.Format("Context data {0} didn't exists.", typeof(T).ToString()));
                }
                else
                {
                    if (!(obj is T))
                    {
                        throw new UnmatchedContextDataException(string.Format("Context data is not {0}.", typeof(T).ToString()));
                    }
                    return (T)obj;
                }
            }
        }

        public void Dispose()
        {
            object obj = Current;
            if (obj != null && obj is IDisposable)
            {
                (obj as IDisposable).Dispose();
            }
            CallContext.FreeNamedDataSlot(GetKey());
        }

        public void Init(Func<T> creator)
        {
            CallContext.SetData(GetKey(), creator());
        }

        protected abstract string GetKey();
    }
}
